package com.hlyj.http.base.tool.lib_hlyj_base.net;

import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.cszy.mfjx.lib_hlyj_base.BuildConfig;
import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication;
import com.hlyj.http.base.tool.lib_hlyj_base.Constants;
import com.hlyj.http.base.tool.lib_hlyj_base.bean.GetadswitchResultBean;
import com.hlyj.http.base.tool.lib_hlyj_base.listener.IChannelProvider;
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils;
import com.hlyj.http.base.tool.lib_hlyj_base.utils.DeviceModeUtil;
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils;
import com.hnyyac.ad.mds.utils.BaseAdConstants;

import java.io.IOException;
import java.net.URLEncoder;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class LogSendInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {

        Request oldRequest = chain.request();
        String url = oldRequest.url().toString();

        Log.e("qin", "日志上报请求地址：" + url);

        String oaid = BaseModuleSpUtils.getInstance().getString(Constants.OAID);
        GetadswitchResultBean resultBean = MMKVUtils.getObject(Constants.initSwitchResultBean, GetadswitchResultBean.class);
        // 用于存储最终的 oaidValue
        String oaidValue = "";

        if (!TextUtils.isEmpty(oaid)) {
            // 如果 SP 中有 oaid，直接使用
            oaidValue = oaid;
        } else {
            // 用于同步的对象
            final Object lock = new Object();
            // 用于存储最终的 oaidValue
            final String[] tempOaidValue = new String[1];
            Thread oaidThread = new Thread(() -> {
                synchronized (lock) {
                    tempOaidValue[0] = DeviceModeUtil.getInstance().getOaid();
                    // 通知主线程任务已完成
                    lock.notify();
                }
            });
            // 启动线程
            oaidThread.start();
            synchronized (lock) {
                try {
                    // 等待线程完成任务
                    lock.wait();
                    oaidValue = tempOaidValue[0];
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    oaidValue = "";
                }
            }
        }
        String[] headers = {
                "User-Agent", DeviceModeUtil.getInstance().getUserAgent(),
        };
        // Cookie 参数
        String[] cookies = {
                "PRODUCTID", BuildConfig.PROJECTNAME,
                "PKG", DeviceModeUtil.getCurrentPackageName(BaseApplication.instance),
                "CHANNEL",  ((IChannelProvider) BaseApplication.instance).getChannelId(),
                "VER", DeviceModeUtil.getInstance().getAppVersionName(BaseApplication.instance),
                "OAID", oaid,
                "APPCODE",BuildConfig.APPCODE,
                "BRAND", DeviceModeUtil.getInstance().getBuildBrand(),
                "MODEL", DeviceModeUtil.getInstance().getDeviceModel(),
                "HARDWAREINFO", BaseModuleSpUtils.getInstance().getString(Constants.HARDWAREINFO),
                "OSVERSION", Build.VERSION.RELEASE,
                "SESSIONID", String.valueOf(BaseModuleSpUtils.getInstance().getInt(Constants.SESSIONID))
        };
        // 构建 Cookie 字符串
       StringBuilder cookieBuilder = new StringBuilder();
        for (int i = 0; i < cookies.length; i += 2) {
            if (i > 0) {
                cookieBuilder.append(";");
            }
            String key = cookies[i];
            String value = cookies[i + 1];
            if (value != null) {
                value = URLEncoder.encode(value, "UTF-8");//这里不转码报错
            } else {
                value = ""; // or handle null values as needed
            }
            cookieBuilder.append(key).append("=").append(value);
        }
        String cookie = cookieBuilder.toString();
        // 添加 Header 和 Cookie
        Request.Builder requestBuilder = oldRequest.newBuilder()
                .header("Cookie", cookie); // 添加 Cookie 头
// 检查 headers 数组长度是否为偶数
        if (headers.length % 2 == 0) {
            for (int i = 0; i < headers.length; i += 2) {
                requestBuilder.header(headers[i], headers[i + 1]); // 添加 Header 参数
            }
        } else {
            Log.e("qin", "headers 数组长度不是偶数，无法正确处理");
        }
        Log.d("qin", "日志cookie: " + cookie);
        // 打印请求头参数
        Request newRequest = requestBuilder.build();
        return chain.proceed(newRequest);
    }
}